const express = require(`express`);
let Router = express.Router();
const { TOKENPWD } = require(`../util/config`);
// 注册账号
Router.post(`/register`, (req, res) => {
  let { userName, userPwd } = req.body;
  // 判断账号和密码不能为空
  console.log(userName, userPwd);
  if (!userName || !userPwd) {
    res.send({ code: 201, msg: `账号和密码不能为空` });
    return;
  }

  // 判断有没有重复的账号  这个启动mysql要包着下面的 不然这个的条件return 下面还是会运行
  let testSql = `SELECT * FROM user WHERE username = "${userName}" ;`;
  res.execSql(testSql, (err, result) => {
    if (err) {
      res.send({ code: 500, msg: err.message });
      return;
    }
    if (result.length > 0) {
      res.send({ code: 201, msg: `用户名已存在，请重新输入` });
      return;
    }

    let sql = `INSERT INTO user (username,password) VALUES ("${userName}","${userPwd}");`;
    res.execSql(sql, (err, result) => {
      if (err) {
        res.send({ code: 500, msg: err.message });
        return;
      }
      res.send({ code: 200, msg: `注册成功` });
    });
  });
});

// 登录账号
Router.post(`/login`, (req, res) => {
  let { userName, userPwd } = req.body;
  // 判断账号和密码不能为空
  if (!userName || !userPwd) {
    res.send({ code: 201, msg: `账号或密码不能为空` });
    return;
  }
  let sql = `SELECT * FROM user WHERE username = "${userName}" AND password = "${userPwd}";`;
  res.execSql(sql, (err, result) => {
    if (err) {
      res.send({ code: 500, msg: err.message });
      return;
    }
    if (result.length <= 0) {
      res.send({
        code: 201,
        msg: `登陆失败，用户名或密码错误`
      });
      return;
    }
    res.send({ code: 200, msg: `登陆成功`, token: creatToken(userName), });
  });
});

const jwt = require("jsonwebtoken");
function creatToken(userName) {
  //   let token =   jwt.sign({ data: userName(userName为用户密码)}, 'secret'(secret为自己设置的加密密码), { expiresIn: 60 * 60 });
  return (
    `Bearer ` +
    jwt.sign(
      {
        data: userName,
      },
      TOKENPWD,
      { expiresIn: 60 * 60 }
    )
  );
}

// 导出
module.exports = Router;
